package com.cc.data_explore.logic.excel;

import com.cc.data_explore.logic.mybatis.model.FileData;
import lombok.extern.slf4j.Slf4j;
import org.dromara.hutool.core.data.id.IdUtil;
import org.dromara.hutool.core.io.file.FileNameUtil;
import org.dromara.hutool.json.JSONConfig;
import org.dromara.hutool.json.JSONUtil;
import org.dromara.hutool.json.writer.NumberWriteMode;
import org.ttzero.excel.reader.ExcelReader;
import org.ttzero.excel.util.CSVUtil;

import java.io.IOException;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.function.Consumer;

/**
 * @author cc
 * @version 1.0
 * @since 2025/3/28
 */
@Slf4j
public class FileLogic {

    public static Map<String, Integer> readSheetMap(String filePath) {
        Map<String, Integer> sheets = new HashMap<>();
        // 创建 ExcelReader 实例，用于读取 Excel 文件
        try (ExcelReader reader = ExcelReader.read(Path.of(filePath))) {
            // 获取 Excel 文件中的所有工作表
            reader.sheets().forEach(sheet -> sheets.put(sheet.getName(), sheet.getSize()));
        } catch (IOException e) {
            log.error("Error reading Excel file: ", e);
        }
        return sheets;
    }

    public static Map<String, Integer> readSheetMap(String filePath, char delimiter) {
        Map<String, Integer> sheets = new HashMap<>();
        try (CSVUtil.Reader reader = CSVUtil.newReader(Path.of(filePath), delimiter)) {
            String name = FileNameUtil.getName(filePath);
            long count = reader.stream().count();
            sheets.put(name, (int) count);
        } catch (IOException e) {
            log.error("Error reading CSV file: ", e);
        }
        return sheets;
    }


    public static void readData(String filePath, Long fileId, Map<String, Long> sheetIdMap, Consumer<List<FileData>> function) {
        // 创建 ExcelReader 实例，用于读取 Excel 文件
        List<FileData> batch = new ArrayList<>();
        try (ExcelReader reader = ExcelReader.read(Path.of(filePath))) {
            // 获取 Excel 文件中的所有工作表
            reader.sheets().forEach(sheet -> sheet.rows().forEach(row -> {
                int rowNum = row.getRowNum();
                Map<String, Object> map = row.toMap();
                JSONConfig.of().setNumberWriteMode(NumberWriteMode.STRING);
                String jsonStr = JSONUtil.toJsonStr(map);
                long id = IdUtil.getSnowflakeNextId();
                Long sheetId = sheetIdMap.get(sheet.getName());
                batch.add(new FileData(id, fileId, sheetId, rowNum, jsonStr));
            }));
        } catch (IOException e) {
            log.error("Error reading Excel file: ", e);
        }
        function.accept(batch);
    }

}
